package com.xiaomi.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaomi.dto.AlertDTO;
import com.xiaomi.entity.*;
import com.xiaomi.mapper.AlertMapper;
import com.xiaomi.mapper.RuleMapper;
import com.xiaomi.mapper.VehicleMapper;
import com.xiaomi.service.AlertService;
import com.xiaomi.vo.AlertVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AlertServiceImpl implements AlertService {
    @Autowired
    private AlertMapper alertMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private VehicleMapper vehicleMapper;
    /**
     * 根据信息，查找是否需要报警
     * @param signal
     * @return
     */
    @Override
    public AlertRecord getAlertRecordBySingal(Signal signal) {
        return null;
    }

    @Override
    public void save(AlertRecord alert) {
        //查找数据库中有没有车一样，规则一样，相应码一样的，如果有则不需要添加
        if (alertMapper.selectByAlert(alert) == null) {
            //保存新的预警
            alertMapper.save(alert);
        }
    }

    @Override
    public List<AlertVO> getAlert(List<AlertDTO> alertDTOs) {
        List<AlertVO> alertVOS = new ArrayList<>();
        for (AlertDTO alertDTO : alertDTOs) {
            Vehicle vehicle = vehicleMapper.getById(alertDTO.getVehicleFrameNumber());
            List<Rule> rules = ruleMapper.selectByBatteryType(vehicle.getBatteryType());
            //遍历规则，进行判断
            for (Rule rule : rules) {
                if(rule.getRuleCode() == alertDTO.getRuleCode() && alertDTO.getRuleCode() == 1){
                    //解析电压信息

                    AlertVO alertVO = processVoltage(alertDTO, vehicle, rule);
                    alertVOS.add(alertVO);
                }
                if(rule.getRuleCode() == alertDTO.getRuleCode() && alertDTO.getRuleCode() == 2){
                    //解析电流信息

                    AlertVO alertVO1 = processCurrent(alertDTO, vehicle, rule);
                    alertVOS.add(alertVO1);
                }
                if (alertDTO.getRuleCode() == null){
                    if (rule.getRuleCode() == 1){
                        //解析电压信息
                        AlertVO alertVO = processVoltage(alertDTO, vehicle, rule);
                        alertVOS.add(alertVO);
                    }
                    if (rule.getRuleCode() == 2){
                        //解析电流信息
                        AlertVO alertVO1 = processCurrent(alertDTO, vehicle, rule);
                        alertVOS.add(alertVO1);
                    }
                }
            }
        }
        return alertVOS;
    }

    private AlertVO processVoltage(AlertDTO alertDTO, Vehicle vehicle, Rule rule) {
        Condition condition = JSON.parseObject(rule.getConditionJson(), Condition.class);

        Voltage voltage = JSON.parseObject(alertDTO.getSignalJSON(), Voltage.class);
        //计算实际的电压差
        double voltageDiff = voltage.getMx() - voltage.getMi();

        //匹配等级
        int level = matchThreshold(condition.getThresholds(), voltageDiff);
        return AlertVO.builder()
                .vehicleFrameNumber(alertDTO.getVehicleFrameNumber())
                .batteryType(vehicle.getBatteryType())
                .alertLevel(level)
                .alertName(rule.getRuleName())
                .build();
    }
    private AlertVO processCurrent(AlertDTO alertDTO, Vehicle vehicle, Rule rule) {
        Condition condition = JSON.parseObject(rule.getConditionJson(), Condition.class);

        Current current = JSON.parseObject(alertDTO.getSignalJSON(), Current.class);
        //计算实际的电流差
        double currentDiff = current.getIx() - current.getIi();

        //匹配等级
        int level = matchThreshold(condition.getThresholds(), currentDiff);
        return AlertVO.builder()
                .vehicleFrameNumber(alertDTO.getVehicleFrameNumber())
                .batteryType(vehicle.getBatteryType())
                .alertLevel(level)
                .alertName(rule.getRuleName())
                .build();
    }

    private int matchThreshold(List<Threshold> thresholds, double value) {
        //按照min降序排列（确保匹配高优先级规则）
        thresholds.sort((o1, o2) -> Double.compare(o2.getMin(), o1.getMin()));

        for (Threshold threshold : thresholds) {
            if(threshold.getMax()!=null){
                if (value >= threshold.getMin() && value <= threshold.getMax()) {
                    return threshold.getLevel();
                }
            }else {
                if (value >= threshold.getMin())
                    return threshold.getLevel();
            }
        }
        return 0;
    }
}
